import Taro from '@tarojs/taro';
import React, { useEffect, useState } from 'react';
import { View } from '@tarojs/components';

import { getProcessStepImageApi } from '../api/myself';
import ImageLoader from './ImageLoader';

import './NineImage.scss';

interface NineImageProps {
  oneImage?: boolean;
  images: string[] | null;
  stepId?: string | number;
  className?: string;
  height?: number | string;
}

/**
 * 九宫格图片展示组件（微信朋友圈风格）
 * 支持任意数量图片，点击可放大预览
 */
export const NineImage: React.FC<NineImageProps> = ({ oneImage = true, images = [], stepId = "", className = '', height = '25vh' }) => {

  const [processedImages, setProcessedImages] = useState<string[]>([]);
  const [previewImages, setPreviewImages] = useState<string[]>([]);

  
  // 使用ImageLoader组件内部处理异步URL

  const getProcessStepImage = async () => {
    try {
      const res = await getProcessStepImageApi(Number(stepId));
      if (res.code === 200 && res.data && res.data.length > 0) {
        if (oneImage) {
          setProcessedImages([res.data[0].image]);
        } else {
          setProcessedImages(res.data.map((item) => item.image));
        }
        setPreviewImages(res.data.map((item) => item.image));
      }
    } catch (err) {
      console.log(err);
    }
  }

  useEffect(() => {
    if ( images && images.length > 0) {
      setProcessedImages(images);
    }else if (stepId) {
      getProcessStepImage();
    }
  }, []);

  // 处理图片点击预览
  const handleImageClick = (index: number) => {
    Taro.previewImage({
      current: processedImages[index],
      urls: previewImages,
    });
  };

  // 根据图片数量计算样式类名
  const getImageContainerClass = () => {
    if (processedImages.length === 1) {
      return 'single-image';
    } else if (processedImages.length < 5) {
      // 2-4张图片使用2*2布局，3张图片添加额外类
      return processedImages.length === 3 ? 'two-or-four-images three-images' : 'two-or-four-images';
    } else {
      return 'multi-images';
    }
  };

  // 计算图片容器的高度样式
  const getImageWrapperStyle = () => {
    if (height === undefined) return {};
    return {
      height: typeof height === 'number' ? `${height}px` : height
    };
  };

  // 如果没有图片，不渲染任何内容
  if (!processedImages || processedImages.length === 0) {
    return null;
  }

  return (
    <>
      <View className='gray-color text-sm'>点击查看图片详情，图片数量：{previewImages.length}</View>
      <View className={`nine-image-container ${getImageContainerClass()} ${className}`}>
        {processedImages.map((src, index) => (
          <View
              key={index}
              className={`image-wrapper ${index >= 9 ? 'hidden' : ''}`}
              style={getImageWrapperStyle()}
              onClick={() => handleImageClick(index)}
            >
            <ImageLoader
              src={src}
              mode="widthFix"
              lazyLoad
            />
            {index === 8 && processedImages.length > 9 && (
              <View className="image-count-overlay">
                +{processedImages.length - 9}
              </View>
            )}
            {processedImages.length > 1 && (
              <View className="image-index-overlay">
                {index + 1}
              </View>
            )}
          </View>
        ))}
      </View>
    </>
  );
};

export default NineImage;